package com.xml.controller;

import com.xml.util.HttpUtils;
import com.xml.util.TimestampUtil;
import com.xml.vo.MyResponseBeanEnum;
import gridreport.ExportType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URLEncoder;
import java.util.regex.Matcher;

/**
 * @author xml E-Mail:kaioct@qq.com
 * @date 2021/3/24
 * @desc gridreportspringboot
 * @created 2021-03-24 20:49
 **/
@Slf4j
@Controller
@RequestMapping("/report")
public class GridReportServerController {

    @RequestMapping("/pdf")
    @ResponseBody
    public String pdf(Model model,@RequestParam(name = "pdf_mode") String pdf_mode, @RequestParam(name = "grf") String grf, @RequestParam(name = "data_url") String data_url, HttpServletRequest request, HttpServletResponse response) {
        log.info("===在浏览器显示PDF===");
        log.info("grf=" + grf);
        log.info("data_url=" + data_url);

        //PDF文件的显示方式
        // inline内联模式，直接通过浏览器打开PDF；
        // attachment附件模式，浏览器提示保存对话框
        pdf_mode = request.getParameter("pdf_mode") == null ? "inline" : request.getParameter("pdf_mode").toString();


        //POST参数中获取GRF模板JSON数据的基本网址
        String base_url = "";
        //POST参数中获取GRF模板JSON数据的参数
        String param_str = "";
        //获取调用页面中给GRF模板路径的URL
        String grf_url = "";

        //获取grf模板 参数值
        grf_url = request.getParameter("grf") == null ? "" : request.getParameter("grf").toString();
        if (grf_url == null || grf_url.length() == 0) {
            model.addAttribute("errmsg", MyResponseBeanEnum.GRF_ERROR.getMessage());
            return "error";
        }

        //获取当前访问页面完整url
        String full_url = request.getQueryString().toString();
        log.info("full_url:" + full_url);

        //取data_url=后面所有的字符串
        data_url = full_url.substring(full_url.indexOf("data_url=") + 9);
        log.info("data_url:" + data_url);
        if (data_url == null || data_url.length() == 0) {
            model.addAttribute("errmsg", MyResponseBeanEnum.DATA_URL_ERROR.getMessage());
            return "error";
        }

        //1 创建报表对象,此处需要引入gridreport.jar到项目中
        gridreport.Report report = new gridreport.Report();

        //2 从文件载入报表grf模板
        //载入报表网络grf模板文件 如http://www.gridreport.cn/demos/grf/1a.grf
        //log.info("载入互联网模板grf_url:" + grf_url);
        //Boolean grf_load_flag = report.LoadFromURL(grf_url);

        String static_path=getClassPath()+File.separator+"static"+File.separator;
        grf_url=static_path+grf_url;
        log.info("载入本地模板grf_url:" + grf_url);
        Boolean grf_load_flag = report.LoadFromFile(grf_url);
        if (!grf_load_flag) {
            model.addAttribute("errmsg", MyResponseBeanEnum.LOAD_GRF_ERROR.getMessage() + grf_url);
            return "error";
        }

        System.out.println(data_url);
        //3 获取模板对应的JSON数据：模板发送POST请求获取GRF模板的JSON数据
        String reportDataText = HttpUtils.get(data_url);
        log.info("模板JSON数据是:" + reportDataText);
        boolean load_grf_data_flag = report.LoadDataFromXML(reportDataText);
        if (!load_grf_data_flag) {
            model.addAttribute("errmsg", MyResponseBeanEnum.LOAD_GRF_ERROR.getMessage() );
            return "error";
        }

        //4 生成PDF文档数据到二进制数据对象
        gridreport.BinaryObject bo = report.ExportDirectToBinaryObject(ExportType.PDF);

        //获取当前的时间戳作为下载PDF的名字
        String down_pdf_name = TimestampUtil.getCurrentTimestamp() + ".pdf";
        //5 将生成的数据响应给客户端
        try {
            //ServerUtility.ResponseBinary(request, response, bo, down_pdf_name, "application/pdf", "inline");//inline
            //设置response响应头
            response.reset(); //设置页面不缓存,清空buffer
            response.setCharacterEncoding("UTF-8");//字符编码
            response.setContentType("multipart/form-data");
            response.setContentType("application/pdf");
            //二进制传输数据设置响应头
            if("inline".equals(pdf_mode))
                response.setHeader("content-Disposition","inline;fileName="+ URLEncoder.encode(down_pdf_name,"UTF-8"));
            else
                response.setHeader("content-Disposition","attachment;fileName="+ URLEncoder.encode(down_pdf_name,"UTF-8"));

            response.resetBuffer();
            ServletOutputStream os = response.getOutputStream();
            os.write(bo.getDataBuf());
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            /*model.addAttribute("errmsg", MyResponseBeanEnum.LOAD_PDF_ERROR.getMessage() + e.getMessage());
            return "error";*/

        }
        return "success";
    }


    /**
     * 获取项目根路径
     * @return G:\apache-tomcat-8.5.64\webapps\ROOT\WEB-INF\classes
     */
    private static String getClassPath() {
        // 获取跟目录
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            // nothing to do
        }
        if (path == null || !path.exists()) {
            path = new File("");
        }
        String pathStr = path.getAbsolutePath();
        // 如果是在eclipse中运行，则和target同级目录,如果是jar部署到服务器，则默认和jar包同级
        pathStr = pathStr.replace("\\target\\classes", "");
        return pathStr;
    }
}
